﻿using AutoMapper;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using WCS.Entities;
using WCS.Entities.Api;
using WCS.ViewModels;
using Path = System.IO.Path;

namespace WCS.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class ParameterController : ControllerBase
    {
        private readonly IOptionsMonitor<SystemParameter> _options;
        private readonly ILogger<ParameterController> _logger;
        public ParameterController(ILogger<ParameterController> logger,
            IOptionsMonitor<SystemParameter> options)
        {
            _options = options;
            _logger = logger;
        }

        /// <summary>
        /// 获取参数
        /// </summary>
        /// <returns></returns>
        [HttpGet()]
        public ActionResult<ApiResult> GetParameter([FromServices] IMapper mapper)
        {

            try
            {
                return ApiResultHelp.Success(mapper.Map<ParameterDto>(_options.CurrentValue));
            }
            catch (Exception e)
            {
                return ApiResultHelp.Error("查找Park点出错" + e.Message);
            }

        }


        /// <summary>
        /// 获取参数
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<ApiResult> UpdateParameter([FromServices] IMapper mapper, ParameterDto parameterDto)
        {

            try
            {

                var filePath = Path.Combine(Environment.CurrentDirectory, "appsettings.json");
                JObject jsonObject;
                using (StreamReader file = new StreamReader(filePath))
                using (JsonTextReader reader = new JsonTextReader(file))
                {
                    var systemInfo = mapper.Map<SystemParameter>(parameterDto);
                    jsonObject = (JObject)JToken.ReadFrom(reader);
                    jsonObject["SystemSetting"] = JObject.Parse(JsonConvert.SerializeObject(systemInfo));
                }

                using (var writer = new StreamWriter(filePath))
                using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
                {
                    jsonObject.WriteTo(jsonwriter);
                }

                return ApiResultHelp.Success(_options.CurrentValue);

            }
            catch (Exception e)
            {
                return ApiResultHelp.Error("更新出错" + e.Message);
            }

        }
    }
}
